<template>
  <div>
    <el-form ref="formRef" :model="form" size="small" label-width="60" :show-message="false">
      <el-row :gutter="8">
        <el-col :span="6">
          <el-form-item label="用户名称" prop="userName">
            <el-input placeholder="请输入" v-model="form.userName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="角色" prop="role_id">
            <el-select v-model="form.role_id" placeholder="请选择" size="small" clearable>
              <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="el-col-auto">
          <el-form-item>
            <el-button type="primary" @click="search">搜索</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="mt-sm mb-sm text-right">
      <el-button type="danger" size="small" @click="delMulti()">批量删除</el-button>
    </div>
    <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
      <template #is_used="{ row }">
        <el-switch v-model="row.is_used" size="small" @change="isUsedChange(row)" />
      </template>
      <template #control="{ row }">
        <el-popconfirm title="确定要删除吗?" :hide-after="0" @confirm="del(row.user_id)">
          <template #reference>
            <el-button link type="danger">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </el-popconfirm>
      </template>
    </vxe-grid>
  </div>
</template>

<script setup lang="ts">
import '@/styles/common.scss'
import { reactive, ref } from 'vue'
import { CODE, http } from '@/plugins/axios'
import type { VxeGridInstance, VxeGridProps } from 'vxe-table'
import { GRID_BASE_CONFIG, GRID_BASE_MENU_CONFIG, gridEvents } from '@/plugins/vxe-table'
import { notification } from '@/services/common'

const form = reactive({
  userName: '',
  role_id: ''
})

let roleList: any = reactive([])

const gridRef = ref<VxeGridInstance<any>>()

const gridOptions = reactive<VxeGridProps<any>>({
  ...GRID_BASE_CONFIG,
  menuConfig: GRID_BASE_MENU_CONFIG,
  pagerConfig: {
    currentPage: 1,
    pageSize: 10
  },
  proxyConfig: {
    ajax: {
      query: ({ page }) => {
        return getData(page.currentPage, page.pageSize)
      }
    },
    response: {
      result: 'data',
      total: 'count'
    }
  },
  columns: [
    { type: 'checkbox', width: 40 },
    { type: 'seq', title: '序号', width: 60 },
    { field: 'user_name', title: '用户名称', width: 100, sortable: true },
    { field: 'nick_name', title: '用户名称', width: 100 },
    { field: 'role_name', title: '所属角色', width: 70 },
    { field: 'phone', title: '手机号', width: 94 },
    { field: 'create_time', title: '创建时间', width: 130 },
    { field: 'last_login_time', title: '最近登录时间', width: 130 },
    { field: 'is_used', title: '是否启用', slots: { default: 'is_used' } },
    { field: 'control', title: '操作', width: 100, fixed: 'right', slots: { default: 'control' } }
  ]
})

function getData(page: number, pageSize: number) {
  return new Promise((resolve, reject) => {
    const params = {
      userName: form.userName,
      role_id: form.role_id || '',
      page,
      pageSize
    }
    http({
      url: '/api/user/getUserList',
      params
    }).then((res: any) => {
      res.data = res.data.map((item: any) => {
        return {
          ...item,
          is_used: item.is_used === 1
        }
      })
      resolve(res)
    }).catch(() => {
      reject()
    })
  })
}

/** 获取角色列表 */
function getRoleList() {
  const params = {}
  http({
    url: '/api/role/getRoleList',
    params
  }).then((res: any) => {
    res.data.forEach((item: any) => {
      roleList.push({
        label: item.role_name,
        value: item.role_id
      })
    })
  }).catch(() => { })
}

getRoleList()

function search() {
  const $grid = gridRef.value
  if ($grid) {
    $grid.commitProxy('reload')
  }
}

function reset() {
  form.userName = ''
  form.role_id = ''
}

/** 批量删除 */
const delMulti = () => {
  const $grid = gridRef.value;
  if ($grid) {
    const list = $grid.getCheckboxRecords();
    if (!list.length) {
      notification({ message: '请选择要删除的数据', type: 'warning' });
      return;
    }
    const ids = list.map((item: any) => (item.user_id)).join(',');
    del(ids);
  }
}

/** 删除 */
const del = (user_id: any) => {
  return new Promise((resolve, reject) => {
    http({
      url: '/api/user/delUser',
      method: 'post',
      data: {
        user_id
      }
    }).then((res: any) => {
      if (res.code === CODE.SUCCESS) {
        notification({ message: res.msg, type: 'success' });
        gridRef.value?.commitProxy('reload');
      }
      resolve(res)
    }).catch(() => {
      reject()
    })
  })
}

/** 是否启用变更 */
const isUsedChange = (row: any) => {
  return new Promise((resolve, reject) => {
    http({
      url: '/api/user/used',
      method: 'post',
      data: {
        user_id: row.user_id,
        is_used: row.is_used ? 1 : 0
      }
    }).then((res: any) => {
      if (res.code === CODE.SUCCESS) {
        notification({ message: res.msg, type: 'success' });
      }
      resolve(res)
    }).catch(() => {
     reject()
    })
  })
}
</script>

<style lang="scss" scoped></style>
